import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { observer, useLocalStore } from 'mobx-react' // 6.x or mobx-react-lite@1.4.0

export const Todo = ({ onToggle, done, text }: { done: boolean, text: string, onToggle: (text: string) => void }) => {
    return <div onClick={() => { onToggle(text) }} >{done ? "ok" : "no"} {text}</div>
}

function createTodos(lst: string[]): Record<string, boolean> {
    let r = {};
    for (let key of lst)
        r[key] = false;
    return r;
}

type F<S> = (p: S) => JSX.Element;
export const TodoList = observer<F<{ initialTodos: string[] }>>(
    ({ initialTodos }) => {
        const todoRef = React.useRef<HTMLInputElement>()
        const store = useLocalStore(() => ({
            todos: createTodos(initialTodos) as Record<string, boolean>,
            get pendingTodos() {
                return Object.keys(store.todos).filter(todo => store.todos[todo] === false)
            },
            get doneTodos() {
                return Object.keys(store.todos).filter(todo => store.todos[todo] === true)
            },
            addTodo: (e: React.FormEvent<HTMLFormElement>) => {
                e.preventDefault();
                store.todos[todoRef.current.value] = false
                todoRef.current.value = ''
            },
            toggleTodo: (todo: string) => {
                store.todos[todo] = !store.todos[todo]
            },
        }))

        const renderTodo = (done: boolean) => (todo: string) => (
            <Todo key={todo} done={done} text={todo} onToggle={store.toggleTodo} />
        )

        return (
            <form onSubmit={store.addTodo}>
                {store.pendingTodos.map(renderTodo(false))}
                {store.doneTodos.map(renderTodo(true))}
                <br />
                <input ref={todoRef} />
                <button>Add todo</button>
            </form>
        )
    }
)

ReactDOM.render(
    <TodoList
        initialTodos={['Introduce MobX in React', 'Make a great app with MobX']}
    />,
    document.getElementById("app"))
